<template>
	<view class="page-content">
		<!-- <view class="page-top">
			<u-icon @click="goback" name="arrow-left" size="36"></u-icon>
			<text>{{tabTitle}}</text>
			<image @click="goGroupList" v-if="timtypes == 'GROUP'" class="rigth-group" src="../../static/index/group.png" alt=""/>
			<view v-else></view>
		</view> -->
		<view class="content" @touchstart="hideDrawer">
			<!-- :scroll-with-animation="scrollAnimation" -->
			<scroll-view class="msg-list" scroll-y="true"
				:scroll-top="scrollTop" :scroll-into-view="scrollToView" @scrolltoupper="loadHistory"
				upper-threshold="50">
				<!-- 加载历史数据waitingUI -->
				<view v-if="isHistoryLoading" class="loading">
					<view class="spinner">
						<view class="rect1"></view>
						<view class="rect2"></view>
						<view class="rect3"></view>
						<view class="rect4"></view>
						<view class="rect5"></view>
					</view>
				</view>
				<view class="row" v-for="(item,index) in msgList" :key="index" :id="item.ID">
					<template v-if="timtypes === 'C2C' || timtypes === 'GROUP'">
						<!-- 用户消息 -->
						<view v-if="item.payload.data == 'group_create'" class="row_time">
						{{timeFliter(item.time)}}
						<br/>
						创建了群聊
						</view>
						<view v-else class="row_time">{{timeFliter(item.time)}}</view>
						<!-- 用户系统消息 -->
						<template v-if="item._elements[0].type === 'TIMGroupTipElem'">
							<block v-for="(i,ind) in toUserInfos" :key='ind'>
								<view class="systemtxt" v-if="i.id === parseInt(item._elements[0].content.operatorID)">
									{{i.nickname}} 修改群信息
								</view>
							</block>
						</template>
						<template v-else-if="item._elements[0].type === 'TIMCustomElem'">
							<block v-for="(i,ind) in toUserInfos" :key='ind'>
								<view class="systemtxt" v-if="i.id === parseInt(item.from)">{{i.nickname}}{{item._elements[0].content.extension}}
								</view>
							</block>
						</template>
						<template v-else>
							<!-- 自己发出的消息 -->
							<view class="my" v-if="item.flow=='out'">
								<!-- 左-消息 -->
								<view class="left">
									<view class="left_statu" v-if="timtypes === 'C2C'" :style="{color:item.isPeerRead?'#999':'#198FFF'}">{{item.isPeerRead?'已读':'未读'}}</view>
									<!-- 文字消息 -->
									<view v-if="item.type==TIM.TYPES.MSG_TEXT" class="bubble">
										<rich-text :nodes="nodesFliter(item.payload.text)"></rich-text>
									</view>
									<view class="bubble-r" v-if="item.type==TIM.TYPES.MSG_TEXT"></view>
									<!-- 图片消息 -->
									<view v-if="item.type==TIM.TYPES.MSG_IMAGE" class="bubble img"
										@tap="showPic(item._elements[0].content.imageInfoArray[0].imageUrl)">
										<image :src="item._elements[0].content.imageInfoArray[0].imageUrl"
											:style="{'width': item._elements[0].content.imageInfoArray[0].width+'px','height': item._elements[0].content.imageInfoArray[0].height+'px'}">
										</image>
									</view>
								</view>
								<!-- 右-头像 -->
								<view class="right">
									<image @click="goUser(userInfos)" :src="userInfo.img || $mAssetsPath.icon_mrtx"></image>
								</view>
							</view>
							<!-- 别人发出的消息 -->
							<view class="other" v-else>
								<!-- 单聊 -->
								<template v-if="item.conversationType === 'C2C'">
									<!-- 左单聊-头像 -->
									<view class="left">
										<image @click="goUser(userInfos)" :src="toUserInfo.img || $mAssetsPath.icon_mrtx"></image>
									</view>
									<!-- 右单聊-消息 -->
									<view class="right">
										<!-- 文字消息 -->
										<view class="bubble-l" v-if="item.type==TIM.TYPES.MSG_TEXT" :style="{'margin-top':item.conversationType==='GROUP'?'12rpx':'25rpx'} "></view>
										<view v-if="item.type==TIM.TYPES.MSG_TEXT" class="bubble">
											<rich-text :nodes="nodesFliter(item.payload.text)"></rich-text>
										</view>
										<!-- 图片消息 -->
										<view v-if="item.type==TIM.TYPES.MSG_IMAGE" class="bubble img"
											@tap="showPic(item._elements[0].content.imageInfoArray[0].imageUrl)">
											<image :src="item._elements[0].content.imageInfoArray[0].imageUrl"
												:style="{'width': item._elements[0].content.imageInfoArray[0].width+'px','height': item._elements[0].content.imageInfoArray[0].height+'px'}">
											</image>
										</view>
									</view>
								</template>
								<!-- 群聊 -->
								<template v-else-if="item.conversationType === 'GROUP'">
									<!-- 左群聊-头像 -->
									<view class="left">
										<block v-for="(i,ind) in toUserInfos" :key='ind'>
											<image @click="goUser(i)" :src="i.img || $mAssetsPath.icon_mrtx"
												v-if="i.id === item.from"></image>
										</block>
									</view>
									<!-- 右群聊-用户名称-时间-消息 -->
									<view class="right">
										<template v-if="item.conversationType === 'GROUP'">
											<block v-for="(i,ind) in toUserInfos" :key='ind'>
												<view class="username" v-if="i.id === item.from">
													<view class="name">{{i.nickname}}</view>
													<!-- <view class="time">{{timeFliter(item.time)}}</view> -->
												</view>
											</block>
										</template>
										<!-- 文字消息 -->
										<view class="bubble-l" v-if="item.type==TIM.TYPES.MSG_TEXT" :style="{'margin-top':item.conversationType==='GROUP'?'12rpx':'25rpx'} "></view>
										<view v-if="item.type==TIM.TYPES.MSG_TEXT" class="bubble">
											<rich-text :nodes="nodesFliter(item.payload.text)"></rich-text>
										</view>
										<!-- 图片消息 -->
										<view v-if="item.type==TIM.TYPES.MSG_IMAGE" class="bubble img"
											@tap="showPic(item._elements[0].content.imageInfoArray[0].imageUrl)">
											<image :src="item._elements[0].content.imageInfoArray[0].imageUrl"
												:style="{'width': item._elements[0].content.imageInfoArray[0].width+'px','height': item._elements[0].content.imageInfoArray[0].height+'px'}">
											</image>
										</view>
									</view>
								</template>
							</view>
						</template>
					</template>
					<template v-else-if="timtypes === 'SYSTEM'">
						<!-- 用户消息 -->
						<view class="row_time">{{item.create_time}}</view>
						<!-- 系统消息 -->
						<view class="other">
							<!-- 单聊 -->
							<!-- 左单聊-头像 -->
							<view class="left">
								<image :src="$mAssetsPath.icon_sys"></image>
							</view>
							<!-- 右单聊-消息 -->
							<view class="right">
								<!-- 文字消息 -->
								<view class="bubble">
									<rich-text :nodes="nodesFliter(item.content.msg)"></rich-text>
								</view>
							</view>
						</view>

					</template>
				</view>
			</scroll-view>
		</view>
		<!-- 抽屉栏 -->
		<view class="popup-layer" :class="popupLayerClass" @touchmove.stop.prevent="discard">
			<!-- 表情 -->
			<swiper class="emoji-swiper" :class="{hidden:hideEmoji}" indicator-dots="true" duration="150">
				<swiper-item v-for="(page,pid) in emojiList" :key="pid">
					<view v-for="(em,eid) in page" :key="eid" @tap="addEmoji(em)">
						<image mode="widthFix" :src="'/static/img/newEmoji/'+em.url"></image>
					</view>
				</swiper-item>
			</swiper>
			<!-- 更多功能 相册-拍照-红包 -->
			<view class="more-layer" :class="{hidden:hideMore}">
				<view class="list">
					<view class="box" @tap="chooseImage">
						<view class="icon tupian2"></view>
					</view>
					<view class="box" @tap="camera">
						<view class="icon paizhao"></view>
					</view>
					<!-- <view class="box" @tap="handRedEnvelopes">
						<view class="icon hongbao"></view>
					</view> -->
				</view>
			</view>
		</view>
		<!-- 底部输入栏 -->
		<view class="input-box" :class="popupLayerClass" @touchmove.stop.prevent="discard" v-if="is_input">
			<!-- H5下不能录音，输入栏布局改动一下 -->
			<!-- #ifndef H5 || APP-->
			<view class="voice">
				<view class="icon" :class="isVoice?'jianpan':'yuyin'" @tap="switchVoice"></view>
			</view>
			<!-- #endif -->
			<!-- #ifdef H5 || APP -->
			<view class="more" @tap="showMore">
				<view class="icon add"></view>
			</view>
			<!-- #endif -->
			<view class="textbox">
				<view class="voice-mode" :class="[isVoice?'':'hidden',recording?'recording':'']"
					@touchstart="voiceBegin" @touchmove.stop.prevent="voiceIng" @touchend="voiceEnd"
					@touchcancel="voiceCancel">{{voiceTis}}</view>
				<view class="text-mode" :class="isVoice?'hidden':''">
					<view class="box">
						<input class="uni-input" cursor-spacing="10" :adjust-position="true" v-model="textMsg" @focus="textareaFocus" />
					</view>
					<view class="em" @tap="chooseEmoji">
						<view class="icon biaoqing"></view>
					</view>
				</view>
			</view>
			<!-- #ifndef H5 || APP-->
			<view class="more" @tap="showMore">
				<view class="icon add"></view>
			</view>
			<!-- #endif -->
			<view class="send" :class="isVoice?'hidden':''" @tap="sendText">
				<view class="btn">发送</view>
			</view>
		</view>
		<!-- 录音UI效果 -->
		<view class="record" :class="recording?'':'hidden'">
			<view class="ing" :class="willStop?'hidden':''">
				<view class="icon luyin2"></view>
			</view>
			<view class="cancel" :class="willStop?'':'hidden'">
				<view class="icon chehui"></view>
			</view>
			<view class="tis" :class="willStop?'change':''">{{recordTis}}</view>
		</view>
		<!-- 红包弹窗 -->
		<view class="windows" :class="windowsState">
			<!-- 遮罩层 -->
			<view class="mask" @touchmove.stop.prevent="discard" @tap="closeRedEnvelope"></view>
			<view class="layer" @touchmove.stop.prevent="discard">
				<view class="open-redenvelope">
					<view class="top">
						<view class="close-btn">
							<view class="icon close" @tap="closeRedEnvelope"></view>
						</view>
						<image src="/static/img/im/face/face_1.jpg"></image>
					</view>
					<view class="from">来自{{redenvelopeData.from}}</view>
					<view class="blessing">{{redenvelopeData.blessing}}</view>
					<view class="money">{{redenvelopeData.money}}</view>
					<view class="showDetails" @tap="toDetails(redenvelopeData.rid)">
						查看领取详情 <view class="icon to"></view>
					</view>
				</view>
			</view>

		</view>
	</view>
</template>
<script>
	//import userList from '../../commen/tim/user.js'
	import TIM from 'tim-js-sdk';
	import store from '@/store';
	import {
		mapGetters,
		mapActions,
		mapState
	} from 'vuex';
	import {
		getTimUserSigs,
		getTimUserInfos,
		getCrowdUserLists,
		getSystemMsgLists,
		getCompanyUserInfos,
		getMailLists, //通讯录
	} from '@/common/api.js';
	export default {
		data() {
			return {
				//TIM变量
				conversationActive: null,
				toUserId: '',
				toUserInfo: {},
				toUserInfos: [],
				userInfos: null,
				nextReqMessageID: '',
				count: 15,
				isCompleted: '',
				msgList: [],
				TIM: null,
				is_input: true,


				//文字消息
				textMsg: '',
				//消息列表
				isHistoryLoading: false,
				scrollAnimation: false,
				scrollTop: 0,
				scrollToView: '',

				msgImgList: [],
				myuid: 0,

				//录音相关参数
				// #ifndef H5
				//H5不能录音
				RECORDER: uni.getRecorderManager(),
				// #endif
				isVoice: false,
				voiceTis: '按住 说话',
				recordTis: "手指上滑 取消发送",
				recording: false,
				willStop: false,
				initPoint: {
					identifier: 0,
					Y: 0
				},
				recordTimer: null,
				recordLength: 0,

				//播放语音相关参数
				AUDIO: uni.createInnerAudioContext(),
				playMsgid: null,
				VoiceTimer: null,
				// 抽屉参数
				popupLayerClass: '',
				// more参数
				hideMore: true,
				//表情定义
				hideEmoji: true,
				emojiList: this.$commen.getEmojiList(),
				//表情图片图床名称 ，由于我上传的第三方图床名称会有改变，所以有此数据来做对应，您实际应用中应该不需要
				onlineEmoji: {
					"100.gif": "AbNQgA.gif",
					"101.gif": "AbN3ut.gif",
					"102.gif": "AbNM3d.gif",
					"103.gif": "AbN8DP.gif",
					"104.gif": "AbNljI.gif",
					"105.gif": "AbNtUS.gif",
					"106.gif": "AbNGHf.gif",
					"107.gif": "AbNYE8.gif",
					"108.gif": "AbNaCQ.gif",
					"109.gif": "AbNN4g.gif",
					"110.gif": "AbN0vn.gif",
					"111.gif": "AbNd3j.gif",
					"112.gif": "AbNsbV.gif",
					"113.gif": "AbNwgs.gif",
					"114.gif": "AbNrD0.gif",
					"115.gif": "AbNDuq.gif",
					"116.gif": "AbNg5F.gif",
					"117.gif": "AbN6ET.gif",
					"118.gif": "AbNcUU.gif",
					"119.gif": "AbNRC4.gif",
					"120.gif": "AbNhvR.gif",
					"121.gif": "AbNf29.gif",
					"122.gif": "AbNW8J.gif",
					"123.gif": "AbNob6.gif",
					"124.gif": "AbN5K1.gif",
					"125.gif": "AbNHUO.gif",
					"126.gif": "AbNIDx.gif",
					"127.gif": "AbN7VK.gif",
					"128.gif": "AbNb5D.gif",
					"129.gif": "AbNX2d.gif",
					"130.gif": "AbNLPe.gif",
					"131.gif": "AbNjxA.gif",
					"132.gif": "AbNO8H.gif",
					"133.gif": "AbNxKI.gif",
					"134.gif": "AbNzrt.gif",
					"135.gif": "AbU9Vf.gif",
					"136.gif": "AbUSqP.gif",
					"137.gif": "AbUCa8.gif",
					"138.gif": "AbUkGQ.gif",
					"139.gif": "AbUFPg.gif",
					"140.gif": "AbUPIS.gif",
					"141.gif": "AbUZMn.gif",
					"142.gif": "AbUExs.gif",
					"143.gif": "AbUA2j.gif",
					"144.gif": "AbUMIU.gif",
					"145.gif": "AbUerq.gif",
					"146.gif": "AbUKaT.gif",
					"147.gif": "AbUmq0.gif",
					"148.gif": "AbUuZV.gif",
					"149.gif": "AbUliF.gif",
					"150.gif": "AbU1G4.gif",
					"151.gif": "AbU8z9.gif",
					"152.gif": "AbU3RJ.gif",
					"153.gif": "AbUYs1.gif",
					"154.gif": "AbUJMR.gif",
					"155.gif": "AbUadK.gif",
					"156.gif": "AbUtqx.gif",
					"157.gif": "AbUUZ6.gif",
					"158.gif": "AbUBJe.gif",
					"159.gif": "AbUdIO.gif",
					"160.gif": "AbU0iD.gif",
					"161.gif": "AbUrzd.gif",
					"162.gif": "AbUDRH.gif",
					"163.gif": "AbUyQA.gif",
					"164.gif": "AbUWo8.gif",
					"165.gif": "AbU6sI.gif",
					"166.gif": "AbU2eP.gif",
					"167.gif": "AbUcLt.gif",
					"168.gif": "AbU4Jg.gif",
					"169.gif": "AbURdf.gif",
					"170.gif": "AbUhFS.gif",
					"171.gif": "AbU5WQ.gif",
					"172.gif": "AbULwV.gif",
					"173.gif": "AbUIzj.gif",
					"174.gif": "AbUTQs.gif",
					"175.gif": "AbU7yn.gif",
					"176.gif": "AbUqe0.gif",
					"177.gif": "AbUHLq.gif",
					"178.gif": "AbUOoT.gif",
					"179.gif": "AbUvYF.gif",
					"180.gif": "AbUjFU.gif",
					"181.gif": "AbaSSJ.gif",
					"182.gif": "AbUxW4.gif",
					"183.gif": "AbaCO1.gif",
					"184.gif": "Abapl9.gif",
					"185.gif": "Aba9yR.gif",
					"186.gif": "AbaFw6.gif",
					"187.gif": "Abaiex.gif",
					"188.gif": "AbakTK.gif",
					"189.gif": "AbaZfe.png",
					"190.gif": "AbaEFO.gif",
					"191.gif": "AbaVYD.gif",
					"192.gif": "AbamSH.gif",
					"193.gif": "AbaKOI.gif",
					"194.gif": "Abanld.gif",
					"195.gif": "Abau6A.gif",
					"196.gif": "AbaQmt.gif",
					"197.gif": "Abal0P.gif",
					"198.gif": "AbatpQ.gif",
					"199.gif": "Aba1Tf.gif",
					"200.png": "Aba8k8.png",
					"201.png": "AbaGtS.png",
					"202.png": "AbaJfg.png",
					"203.png": "AbaNlj.png",
					"204.png": "Abawmq.png",
					"205.png": "AbaU6s.png",
					"206.png": "AbaaXn.png",
					"207.png": "Aba000.png",
					"208.png": "AbarkT.png",
					"209.png": "AbastU.png",
					"210.png": "AbaB7V.png",
					"211.png": "Abafn1.png",
					"212.png": "Abacp4.png",
					"213.png": "AbayhF.png",
					"214.png": "Abag1J.png",
					"215.png": "Aba2c9.png",
					"216.png": "AbaRXR.png",
					"217.png": "Aba476.png",
					"218.png": "Abah0x.png",
					"219.png": "Abdg58.png"
				},
				//红包相关参数
				windowsState: '',
				redenvelopeData: {
					rid: null, //红包ID
					from: null,
					face: null,
					blessing: null,
					money: null
				},
				timtypes: '',
				tabTitle: '',
				id: '',
				params:{
					company_id:0
				},
			};
		},
		computed: {
			...mapGetters(['userInfo', 'userSig','companyInfo','contactList']),
			...mapState({
				currentMessageList: state => state.currentMessageList,
			})
		},
		watch: {
			currentMessageList(newVal, oldVal) {
				console.log(999, newVal)
				let timtype = ''
				let _self = this;
				if (newVal && newVal.length > 0) {
					newVal.forEach(item => {
						if (item.conversationType === 'C2C') {
							timtype = 'C2C';
							if(item.to === (_self.companyInfo.id + ':' + _self.userInfo.uid)){
								//设置为已读
								let promise = _self.tim.setMessageRead({
									conversationID: _self.conversationActive.conversationID
								});
								promise.then(function(imResponse) {
									console.log('全部已读')
									// 已读上报成功
								}).catch(function(imError) {
									// 已读上报失败
									console.log('setMessageRead error:', imError);
								});
							}
						} else if (item.conversationType === 'GROUP') {
							timtype = 'GROUP'
						}
					})
				}
				if (timtype === this.timtypes) {
					this.msgList = newVal
					console.log(123,this.msgList)
					this.screenMsg(newVal, oldVal)
				}
			}
		},
		onLoad(option) {
			console.log(222,option)
			this.id = option.id
			this.params.company_id = this.companyInfo.id;
			console.log(this.emojiList, 'emoji')
			let _self = this;
			this.tabTitle = option.name;
			this.timtypes = option.type;
			console.log(this.timtypes,'这事标题')
			if (option.name && option.type === 'C2C') {
				this.timtypes = option.type
				// 导航栏多语言
				uni.setNavigationBarTitle({
					title: option.name
				});
			} else if (option.name && option.type === 'GROUP') {
				this.timtypes = option.type
				// 导航栏多语言
				uni.setNavigationBarTitle({
					title: option.name
				});
			} else if (option.type === 'SYSTEM') {
				this.timtypes = option.type
				// 导航栏多语言
				uni.setNavigationBarTitle({
					title: '系统消息'
				});
			}
			if (this.timtypes === 'C2C' || this.timtypes === 'GROUP') { //单聊 群聊
				this.userInfos = this.userInfo; //JSON.parse(uni.getStorageSync('userInfos'))
				this.toUserId = this.$store.state.toUserId
				this.conversationActive = this.$store.state.conversationActive
				console.log(2233,this.conversationActive)
				this.TIM = this.$TIM
				//获取聊天对象的用户信息
				if (option.type === 'C2C') {
					getCompanyUserInfos({
						uid: this.toUserId.split(':')[1] ? this.toUserId.split(':')[1] : this.toUserId,
						company_id:this.params.company_id
					}).then(res => {
						if (res.code === 2000) {
							this.toUserInfo = res.data;
						}
					})
				} else if (option.type === 'GROUP') {
					/* getMailLists({
						company_id: this.params.company_id,
						type:'1'
					}).then(res=>{
						if(res.code === 2000){
							
						}
					}) */
					this.toUserInfos = this.contactList.map((item)=>({
						id:this.companyInfo.id +':'+ item.uid,
						img:item.img,
						nickname:item.nickname
					}));
					console.log(333,this.toUserInfos)
				}
				this.getMsgList();
			} else if (this.timtypes === 'SYSTEM') { //系统消息
				this.is_input = false
				this.getSysMsgList();
			}

			//语音自然播放结束
			this.AUDIO.onEnded((res) => {
				this.playMsgid = null;
			});
			// #ifndef H5
			//录音开始事件
			this.RECORDER.onStart((e) => {
				this.recordBegin(e);
			})
			//录音结束事件
			this.RECORDER.onStop((e) => {
				this.recordEnd(e);
			})
			// #endif
		},
		onShow() {
			this.scrollTop = 9999999;
			this.gettitle();
		},
		onUnload() {
			if (this.timtypes === 'C2C' || this.timtypes === 'GROUP' || this.timtypes === 'SYSTEM') {
				//退出页面 将所有的会话内的消息设置为已读
				let promise = this.tim.setMessageRead({
					conversationID: this.conversationActive.conversationID
				});
				promise.then(function(imResponse) {
					console.log('全部已读')
					// 已读上报成功
				}).catch(function(imError) {
					// 已读上报失败
					console.log('setMessageRead error:', imError);
				});
			}
		},
		onNavigationBarButtonTap(e) {
			console.log(23, e)
			if (e.index == 0) {
				uni.navigateTo({
					url: `/pages/message/messageInfoDet?title=${this.tabTitle}&chat_type=${this.timtypes}&id=${this.id}`
				})
			}
		},
		methods: {
			gettitle(){
				if(this.timtypes === 'GROUP'){
					let promise = this.tim.getGroupProfile({ groupID: this.id});
					promise.then(function(imResponse) {
					  console.log('群信息',imResponse.data.group);
					  // 导航栏多语言
					  uni.setNavigationBarTitle({
					  	title: imResponse.data.group.name
					  });
					  
					}).catch(function(imError) {
					  console.warn('getGroupProfile error:', imError); // 获取群详细资料失败的相关信息
					});
				}
			},
			goback(){
				uni.navigateBack();
			},
			goGroupList() {
				uni.setStorageSync('toUserInfos', this.toUserInfos)
				if(this.timtypes != 'GROUP') return
				uni.navigateTo({
					url: `/pages/message/groupList?id=${this.id}`
				})
			},
			//跳转到用户详情页
			goUser(val){
				console.log(val)
				uni.navigateTo({
					url: `/pages/discover/user-index?id=${val.id}`
				})
			},
			// 预览图片
			showPic(msg) {
				uni.previewImage({
					indicator: "none",
					current: msg.content.url,
					urls: this.msgImgList
				});
			},
			//聊天的节点加上外层的div
			nodesFliter(str) {
				let nodeStr = '<div style="align-items: center;word-wrap:break-word;">' + str + '</div>'
				return nodeStr
			},
			//时间过滤
			timeFliter(timer) {
				let timeData = new Date(timer * 1000)
				let str = this.$commen.dateTimeFliter(timeData)
				return str
			},
			// 接受消息(定位消息)
			screenMsg(newVal, oldVal) {
				if (newVal[0] && oldVal[0] && newVal[0].ID && oldVal[0].ID) {
					if (newVal[0].ID != oldVal[0].ID && newVal.length >= this.count) {
						this.$nextTick(() => {
							console.log('定位')
							this.scrollToView = oldVal[0].ID
						});
					} else {
						this.$nextTick(() => {
							this.scrollToView = newVal[newVal.length - 1].ID
						});
					}
				} else {
					this.$nextTick(() => {
						this.scrollToView = newVal[newVal.length - 1].ID
					});
				}
			},
			//触发滑动到顶部(加载历史信息记录)
			loadHistory(e) {
				let that = this
				this.isHistoryLoading = true
				// 更多消息列表
				let conversationID = this.conversationActive.conversationID
				let promise = this.tim.getMessageList({
					conversationID: conversationID,
					nextReqMessageID: this.nextReqMessageID,
					count: this.count
				});
				promise.then((res) => {
					console.log('会话列表：',res)
					if (res.data.messageList.length) {
						that.$store.commit('unshiftCurrentMessageList', res.data.messageList)
						that.nextReqMessageID = res.data.nextReqMessageID // 用于续拉，分页续拉时需传入该字段。
						that.isCompleted = res.data.isCompleted
						//that.scrollToView = res.data.messageList[res.data.messageList.length - 1].ID
					}

				});
				//这段代码很重要，不然每次加载历史数据都会跳到顶部
				// this.$nextTick(function() {
				// 	//this.scrollToView = this.nextReqMessageID; //跳转上次的第一行信息位置
				// 	this.$nextTick(function() {
				// 		this.scrollAnimation = true; //恢复滚动动画
				// 	});

				// });
				this.isHistoryLoading = false;
			},
			getSysMsgList() {
				getSystemMsgLists().then(res => {
					if (res.code === 2000) {
						this.msgList = res.data;
						console.log(111111, this.msgList)
					}
				})
				// 滚动到底部
				this.$nextTick(function() {
					console.log('滚动到底部')
					//进入页面滚动到底部
					this.scrollTop = 9999;
					this.$nextTick(function() {
						this.scrollAnimation = true;
					});
				});
			},
			// 加载初始页面消息
			getMsgList() {
				// 历史消息列表
				let that = this
				let conversationID = this.conversationActive.conversationID
				let promise = this.tim.getMessageList({
					conversationID: conversationID,
					count: this.count
				});
				promise.then((res) => {
					if(res.data.messageList.length) {
						that.$store.commit('pushCurrentMessageList', res.data.messageList)
						that.nextReqMessageID = res.data.nextReqMessageID // 用于续拉，分页续拉时需传入该字段。
						that.isCompleted = res.data.isCompleted
						that.scrollToView = res.data.messageList[0].ID
					}
				});
				// 滚动到底部
				this.$nextTick(function() {
					//进入页面滚动到底部
					this.scrollTop = 9999;
					this.$nextTick(function() {
						//this.scrollAnimation = true;
					});
				});
			},
			//处理图片尺寸，如果不处理宽高，新进入页面加载图片时候会闪
			setPicSize(content) {
				// 让图片最长边等于设置的最大长度，短边等比例缩小，图片控件真实改变，区别于aspectFit方式。
				let maxW = uni.upx2px(350); //350是定义消息图片最大宽度
				let maxH = uni.upx2px(350); //350是定义消息图片最大高度
				if (content.w > maxW || content.h > maxH) {
					let scale = content.w / content.h;
					content.w = scale > 1 ? maxW : maxH * scale;
					content.h = scale > 1 ? maxW / scale : maxH;
				}
				return content;
			},
			//更多功能(点击+弹出)
			showMore() {
				this.isVoice = false;
				this.hideEmoji = true;
				if (this.hideMore) {
					this.hideMore = false;
					this.openDrawer();
				} else {
					this.hideDrawer();
				}
			},
			// 打开抽屉
			openDrawer() {
				this.popupLayerClass = 'showLayer';
			},
			// 隐藏抽屉
			hideDrawer() {
				this.popupLayerClass = '';
				setTimeout(() => {
					this.hideMore = true;
					this.hideEmoji = true;
				}, 150);
			},
			// 选择图片发送
			chooseImage() {
				this.getImage('album');
			},
			//拍照发送
			camera() {
				this.getImage('camera');
			},
			//发红包
			handRedEnvelopes() {
				uni.navigateTo({
					url: 'HM-hand/HM-hand'
				});
				this.hideDrawer();
			},
			//选照片 or 拍照
			getImage(type) {
				this.hideDrawer();
				uni.chooseImage({
					sourceType: [type],
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					success: (res) => {
						console.log(1234, res)
						for (let i = 0; i < res.tempFilePaths.length; i++) {
							uni.getImageInfo({
								src: res.tempFilePaths[i],
								success: (image) => {
									console.log(image.width);
									console.log(image.height);
									let msg = {
										url: res.tempFilePaths[i],
										w: image.width,
										h: image.height
									};
									this.sendMsg(res, 'img');
								}
							});
						}
					}
				});
			},
			// 选择表情
			chooseEmoji() {
				this.hideMore = true;
				if (this.hideEmoji) {
					this.hideEmoji = false;
					this.openDrawer();
				} else {
					this.hideDrawer();
				}
			},
			//添加表情
			addEmoji(em) {
				this.textMsg += em.alt;
			},

			//获取焦点，如果不是选表情ing,则关闭抽屉
			textareaFocus() {
				if (this.popupLayerClass == 'showLayer' && this.hideMore == false) {
					this.hideDrawer();
				}
			},
			// 发送文字消息
			sendText() {
				this.hideDrawer(); //隐藏抽屉
				if (!this.textMsg) {
					return;
				}
				let content = this.replaceEmoji(this.textMsg);
				let msg = {
					text: content
				}
				this.sendMsg(msg, 'text');
				this.textMsg = ''; //清空输入框
			},
			//替换表情符号为图片
			replaceEmoji(str) {
				let replacedStr = str.replace(/\[([^(\]|\[)]*)\]/g, (item, index) => {
					console.log("item: " + item);
					for (let i = 0; i < this.emojiList.length; i++) {
						let row = this.emojiList[i];
						for (let j = 0; j < row.length; j++) {
							let EM = row[j];
							if (EM.alt == item) {
								//在线表情路径，图文混排必须使用网络路径，请上传一份表情到你的服务器后再替换此路径
								//比如你上传服务器后，你的100.gif路径为https://www.xxx.com/emoji/100.gif 则替换onlinePath填写为https://www.xxx.com/emoji/
								let onlinePath = 'https://swy-bucket.oss-cn-shenzhen.aliyuncs.com/emoji/'
								let imgstr = '<img style="width: 24px" src="' + onlinePath + EM.url + '">';
								console.log("imgstr: " + imgstr);
								return imgstr;
							}
						}
					}
				});
				return replacedStr;
			},

			// 发送消息
			sendMsg(content, type) {
				console.log(77, content, type)
				console.log(77, this.toUserId)
				console.log(77, this.timtypes)
				let _self = this;
				let message;
				if (type === 'text') {
					message = this.tim.createTextMessage({
						to: this.toUserId + '',
						conversationType: this.timtypes,
						payload: {
							text: content.text
						}
					});
				} else if (type === 'img') {
					if (this.timtypes === 'C2C') {
						// 发送图片
						message = _self.tim.createImageMessage({
							to: this.toUserId + '',
							conversationType: TIM.TYPES.CONV_C2C,
							payload: {
								file: content,
							},
							// 消息自定义数据（云端保存，会发送到对端，程序卸载重装后还能拉取到，v2.10.2起支持）
							// cloudCustomData: 'your cloud custom data'
							onProgress: function(event) {
								console.log('file uploading:', event)
							}
						});
					} else if (this.timtypes === 'GROUP') {
						// 发送图片
						message = _self.tim.createImageMessage({
							to: this.toUserId + '',
							conversationType: TIM.TYPES.CONV_GROUP,
							payload: {
								file: content,
							},
							// 消息自定义数据（云端保存，会发送到对端，程序卸载重装后还能拉取到，v2.10.2起支持）
							// cloudCustomData: 'your cloud custom data'
							onProgress: function(event) {
								console.log('file uploading:', event)
							}
						});
					}


				}

				this.$store.commit('pushCurrentMessageList', message)
				let pomise = this.tim.sendMessage(message)
				pomise.then(res => {
					this.$nextTick(() => {
						// 滚动到底
						this.scrollToView = res.data.message.ID
					});
				})
			},

			// 添加文字消息到列表
			addTextMsg(msg) {
				this.msgList.push(msg);
			},
			// 添加语音消息到列表
			addVoiceMsg(msg) {
				this.msgList.push(msg);
			},
			// 添加图片消息到列表
			addImgMsg(msg) {
				msg.msg.content = this.setPicSize(msg.msg.content);
				this.msgImgList.push(msg.msg.content.url);
				this.msgList.push(msg);
			},
			addRedEnvelopeMsg(msg) {
				this.msgList.push(msg);
			},
			// 添加系统文字消息到列表
			addSystemTextMsg(msg) {
				this.msgList.push(msg);
			},
			// 添加系统红包消息到列表
			addSystemRedEnvelopeMsg(msg) {
				this.msgList.push(msg);
			},
			// 打开红包
			openRedEnvelope(msg, index) {
				let rid = msg.content.rid;
				uni.showLoading({
					title: '加载中...'
				});
				console.log("index: " + index);
				//模拟请求服务器效果
				setTimeout(() => {
					//加载数据
					if (rid == 0) {
						this.redenvelopeData = {
							rid: 0, //红包ID
							from: "大黑哥",
							face: "/static/img/im/face/face.jpg",
							blessing: "恭喜发财，大吉大利",
							money: "已领完"
						}
					} else {
						this.redenvelopeData = {
							rid: 1, //红包ID
							from: "售后客服008",
							face: "/static/img/im/face/face_2.jpg",
							blessing: "恭喜发财",
							money: "0.01"
						}
						if (!msg.content.isReceived) {
							// {type:"system",msg:{id:8,type:"redEnvelope",content:{text:"你领取了售后客服008的红包"}}},
							this.sendSystemMsg({
								text: "你领取了" + (msg.userinfo.uid == this.myuid ? "自己" : msg.userinfo
									.username) + "的红包"
							}, 'redEnvelope');
							console.log("this.msgList[index]: " + JSON.stringify(this.msgList[index]));
							this.msgList[index].msg.content.isReceived = true;
						}
					}
					uni.hideLoading();
					this.windowsState = 'show';

				}, 200)
			},

			// 关闭红包弹窗
			closeRedEnvelope() {
				this.windowsState = 'hide';
				setTimeout(() => {
					this.windowsState = '';
				}, 200)
			},
			sendSystemMsg(content, type) {
				let lastid = this.msgList[this.msgList.length - 1].msg.id;
				lastid++;
				let row = {
					type: "system",
					msg: {
						id: lastid,
						type: type,
						content: content
					}
				};
				console.log(123)
				this.screenMsg(row)
			},
			//领取详情
			toDetails(rid) {
				uni.navigateTo({
					url: 'HM-details/HM-details?rid=' + rid
				})
			},
			//预览图片
			showPic(url) {
				let urls = [];
				urls.push(url)
				uni.previewImage({
					urls: urls, // urls是数组
					longPressActions: {
						itemList: ['发送给朋友', '保存图片', '收藏'],
						success: function(data) {
							console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
						},
						fail: function(err) {
							console.log(err.errMsg);
						}
					}
				});
			},
			// 播放语音
			playVoice(msg) {
				this.playMsgid = msg.id;
				this.AUDIO.src = msg.content.url;
				this.$nextTick(function() {
					this.AUDIO.play();
				});
			},
			// 录音开始
			voiceBegin(e) {
				if (e.touches.length > 1) {
					return;
				}
				this.initPoint.Y = e.touches[0].clientY;
				this.initPoint.identifier = e.touches[0].identifier;
				this.RECORDER.start({
					format: "mp3"
				}); //录音开始,
			},
			//录音开始UI效果
			recordBegin(e) {
				this.recording = true;
				this.voiceTis = '松开 结束';
				this.recordLength = 0;
				this.recordTimer = setInterval(() => {
					this.recordLength++;
				}, 1000)
			},
			// 录音被打断
			voiceCancel() {
				this.recording = false;
				this.voiceTis = '按住 说话';
				this.recordTis = '手指上滑 取消发送'
				this.willStop = true; //不发送录音
				this.RECORDER.stop(); //录音结束
			},
			// 录音中(判断是否触发上滑取消发送)
			voiceIng(e) {
				if (!this.recording) {
					return;
				}
				let touche = e.touches[0];
				//上滑一个导航栏的高度触发上滑取消发送
				if (this.initPoint.Y - touche.clientY >= uni.upx2px(100)) {
					this.willStop = true;
					this.recordTis = '松开手指 取消发送'
				} else {
					this.willStop = false;
					this.recordTis = '手指上滑 取消发送'
				}
			},
			// 结束录音
			voiceEnd(e) {
				if (!this.recording) {
					return;
				}
				this.recording = false;
				this.voiceTis = '按住 说话';
				this.recordTis = '手指上滑 取消发送'
				this.RECORDER.stop(); //录音结束
			},
			//录音结束(回调文件)
			recordEnd(e) {
				clearInterval(this.recordTimer);
				if (!this.willStop) {
					console.log("e: " + JSON.stringify(e));
					let msg = {
						length: 0,
						url: e.tempFilePath
					}
					let min = parseInt(this.recordLength / 60);
					let sec = this.recordLength % 60;
					min = min < 10 ? '0' + min : min;
					sec = sec < 10 ? '0' + sec : sec;
					msg.length = min + ':' + sec;
					this.sendMsg(msg, 'voice');
				} else {
					console.log('取消发送录音');
				}
				this.willStop = false;
			},
			// 切换语音/文字输入
			switchVoice() {
				this.hideDrawer();
				this.isVoice = this.isVoice ? false : true;
			},
			discard() {
				return;
			}
		}
	}
</script>
<style lang="scss">
	@import "@/static/css/style.scss";
</style>
<style scoped lang="scss">
	.row_time {
		text-align: center!important;
	}
.page-top {
	padding: 40rpx 30rpx 0;
	display: flex;
	height: 92rpx;
	width: 700rpx;
	justify-content: space-between;
	align-items: center;
	box-sizing: content-box;
	background: #fff;
	position: fixed;
	top: 0rpx;
	z-index: 2;
	border-bottom: 1rpx solid #F2F4F5;

	text{
		font-size: 32rpx;
		font-family: PingFang SC;
		font-weight: bold;
		color: #333333;
	}
	.rigth-group{
		width: 36rpx;
		height: 40rpx;
		z-index: 10;
	}
}
</style>
